const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const {	Model } = require('../models/fictionModel');
const bookPath = path.resolve(__dirname, '../books/');

/*判断是否小说编号*/
const isBookNo = function(str) {
	let flag;
	let letters = str.substring(0, 2);
	let numbers = str.substring(2, 8);
	if(str.length === 10 && letters === 'BK' && !!/^\d+$/.test(numbers)) {
		flag = true;
	} else {
		flag = false;
	}
	return flag
}

/*获取JSON文件数据*/
const getJsonData = function(bookno, callback) {
	let arr = [];
	let bookPathJson = path.join(bookPath, bookno, 'chapter.json');
	fs.exists(bookPathJson, function(exists) {
		if(exists) {
			fs.readFile(bookPathJson, "utf8", function(err, data) {
				if(err) {
					console.log(err);
				}
				arr = JSON.parse(data || '[]');
				callback(arr);
			})
		} else {
			callback(arr);
		}
	});
}

/*写入文件*/
const writeChapterFile = function(req, arr, callback) {
	let obj = {};
	let maxId = 0;
	let bookPathJson = path.join(bookPath, req.params.bookno, 'chapter.json');
	let PrefixInteger = function(num, n) {
		return(Array(n).join(0) + num).slice(-n);
	}
	if(!!arr.length) {
		let idArr = arr.map(x => x.id);
		maxId = Math.max.apply(null, idArr);
	}
	obj.id = Number(maxId) + 1;
	obj.title = req.body.title;
	obj.files = 'C' + PrefixInteger(obj.id, 5);
	arr.push(obj);
	fs.writeFile(bookPathJson, JSON.stringify(arr, null, 4), 'utf8', function(err) {
		if(err) {
			console.log(err);
		}
	})
	fs.writeFile(path.join(bookPath, req.params.bookno, obj.files + '.txt'), req.body.content, 'utf8', function(err) {
		callback(err)
	})
}

router.get('/:bookno', function(req, res, next) {
	if(!isBookNo(req.params.bookno)) {
		if(req.params.bookno !== 'add' || req.params.bookno !== 'edit') {
			res.status(404);
		}
		next();
	} else {
		Model.findOne({
			where: {
				bookno: req.params.bookno
			}
		}).then(data => {
			if(!data){
				res.status(404);
				next();
			}else{
				let datas = JSON.parse(JSON.stringify(data));
				res.render('show_fiction', {
					data: datas
				});
			}
		})
	}
});

//获取小说章节列表
router.get('/:bookno/getChapter', function(req, res, next) {
	let bookPathJson = path.join(bookPath, req.params.bookno, 'chapter.json');
	let checkDir = fs.existsSync(bookPathJson);
	if(!!checkDir){
		let results = fs.readFileSync(bookPathJson,'utf8');
		if(!!results && results.length){
			res.json({
				code:200,
				list:JSON.parse(results).sort((a, b) => a.id - b.id)
			})
		}else{
			res.json({
				code:200,
				list: []
			})
		}
	}
})

//添加小说章节页面
router.get('/:bookno/add', function(req, res, next) {
	res.render('add_chapter', {
		bookno: req.params.bookno,
	});
})

//编辑小说章节页面
router.get('/:bookno/edit', function(req, res, next) {
	let cid = req.query.cid;
	getJsonData(req.params.bookno, function(result) {
		let jdata = result.find(x => x.id == cid);
		let txtPath = path.join(bookPath, req.params.bookno, jdata.files+'.txt');
		fs.readFile(txtPath, "utf8", function(err,data){
			if(err){
				console.log(err);
			}
			res.render('edit_chapter', {
				bookno: req.params.bookno,
				title: jdata.title,
				content: data.replace(/[\r\n]/g, "")
			});
		})
	})
})

//同步章节页面
router.get('/:bookno/sync', function(req, res, next) {
	res.render('sync_chapter');
})

//添加小说章节
router.post('/:bookno/create', function(req, res, next) {
	getJsonData(req.params.bookno, function(result) {
		writeChapterFile(req, result, function(err) {
			if(err) {
				res.json({
					code: -1,
					msg: '添加失败'
				})
			} else {
				res.json({
					code: 200,
					msg: '添加成功'
				})
			}
		})
	})
})

//添加小说章节
router.post('/:bookno/update', function(req, res, next) {
	getJsonData(req.params.bookno, function(result) {
		let bookPathJson = path.join(bookPath, req.params.bookno, 'chapter.json');
		let index = result.findIndex(x => x.id == req.body.id);
		let content = req.body.content.replace(/　/g,'').replace('999小说首发 www.999xs.com m.999xs.com','').replace('999小说更新最快 电脑端:https://www.999xs.com/','').replace(/[\r\n]/g, "");
		result[index].title = req.body.title;
		fs.writeFile(bookPathJson, JSON.stringify(result, null, 4), 'utf8', function(err) {
			if(err) {
				console.log(err);
			}
		})
		fs.writeFile(path.join(bookPath, req.params.bookno, result[index].files + '.txt'), content, 'utf8', function(err) {
			if(err) {
				res.json({
					code: -1,
					msg: '修改失败'
				})
			} else {
				res.json({
					code: 200,
					msg: '修改成功'
				})
			}
		})
	});
})

module.exports = router;